package com.fly.openapi.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 自动化接口版本控制Interceptor
 */
@Slf4j
@Component
public class ApiVersionInterceptor implements HandlerInterceptor
{
    /**
     * 是否启用自动化接口版本控制
     */
    private boolean versionEnable = false;
    
    public void setVersionEnable(boolean versionEnable)
    {
        this.versionEnable = versionEnable;
    }
    
    /**
     * 禁止使用接口urlpath,包含版本号路径信息
     */
    private String[] disableUrlPaths = {"/openapi/v1/test"};
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception
    {
        if (!versionEnable)
        {
            log.info("自动化接口版本控制未启用，全部版本接口均可访问");
            return true;
        }
        String uri = request.getRequestURI();
        if (StringUtils.containsAny(uri, disableUrlPaths))
        {
            log.info("####### {} is disabled in {}", uri, disableUrlPaths);
            throw new RuntimeException("对不起，该版本接口已停止使用：" + uri);
        }
        return true;
    }
}
